<?php
namespace app\admin\controller;

use app\admin\model\AuthRule;
use think\Controller;
use think\Db;
use think\Request;

class Common extends Controller
{

	public function _initialize()
    {
        
        $rule = strtolower(request()->module()."/".request()->controller()."/".request()->action());

        if(!$this->checkAuth($rule,session('admin_id'))){

        	if($rule=='admin/index/index'){
        		$this->error('你没有访问权限',url('admin/login/index'));
        	}else{
        		if (Request::instance()->isAjax()){
        			$this->error('你没有访问权限');
        		}else{
        			exit($this->fetch("public/error"));
        		}
        	}
        }
    }

    public function checkAuth($rule,$admin_id)
    {

    	return true;

    	if(!session('admin_id')){
    		return false;
    	}

    	$roles = Db::name('auth_role')
    		->alias('t1')
	        ->field('*')
	        ->join('auth_admin_role t2',"t1.role_id=t2.role_id")
	        ->where('t2.admin_id',$admin_id)
	        ->select();

	    if(!$roles){
	    	return false;
	    }

	    $rules = [];

	    foreach ($roles as  $role) {
	    	$rules = array_merge($rules,explode(',',$role['rule_id']));
	    }

	    $rules = array_unique($rules);

	    $rules = AuthRule::where('rule_id','in',$rules)->column('rule_name');

	    if(!$rules){
	    	return false;
	    }

	    if(in_array($rule,$rules)){
	    	return true;
	    }else{
	    	return false;
	    }
    }
}